<template>
   <view class="container">
      <scroll-view scroll-y="true" class="content">
         <!-- 图片展示 -->
         <swiper class="swiper" indicator-dots autoplay circular>
            <swiper-item v-for="(url, index) in photoUrls" :key="index">
               <image :src="url" mode="aspectFill" class="swiper-image" @tap="previewImage(url)"></image>
            </swiper-item>
         </swiper>
         
         <!-- 基本信息 -->
         <view class="info-section">
            <view class="title">{{ spot.title }}</view>
            <view class="price">¥{{ spot.pricePerMonth }}/月</view>
            <view class="meta">
               <text class="status">{{ selectDictLabel(statusOptions, spot.status) }}</text>
               <text class="location">{{ spot.address }}</text>
            </view>
         </view>

         <!-- 详细信息 -->
         <view class="detail-section">
            <view class="section-title">详细信息</view>
            <view class="detail-item">
               <text class="label">描述</text>
               <text class="value">{{ spot.description }}</text>
            </view>
            <view class="detail-item">
               <text class="label">最短租期</text>
               <text class="value">{{ spot.minRentalPeriod }}个月</text>
            </view>
            <view class="detail-item">
               <text class="label">可充电</text>
               <text class="value">{{ selectDictLabel(yesNoOptions, spot.isEvCharging) }}</text>
            </view>
            <view class="detail-item">
               <text class="label">可议价</text>
               <text class="value">{{ selectDictLabel(yesNoOptions, spot.isNegotiable) }}</text>
            </view>
            <view class="detail-item">
               <text class="label">车位编号</text>
               <text class="value">{{ spot.parkingNumber }}</text>
            </view>
            <view class="detail-item">
               <text class="label">所在建筑</text>
               <text class="value">{{ spot.buildingName }}</text>
            </view>
            <view class="detail-item">
               <text class="label">楼层</text>
               <text class="value">{{ spot.floor }}</text>
            </view>
         </view>

         <!-- 地图展示 -->
         <view class="map-section">
            <view class="section-title">位置信息</view>
            <map class="map" :latitude="spot.latitude" :longitude="spot.longitude" :markers="markers" show-location>
            </map>
         </view>
      </scroll-view>

      <!-- 已发送过意向时显示意向内容 -->
      <view class="apply-info" v-if="myApply">
         <view class="apply-tip">我的意向（仅您和车位主人可见）</view>
         <view class="apply-content">
            <view class="apply-item">
               <text class="label">联系电话</text>
               <text class="value">{{myApply.phone}}</text>
            </view>
            <view class="apply-item">
               <text class="label">期望价格</text>
               <text class="value">{{myApply.pricePerMonth}}元/月</text>
            </view>
            <view class="apply-item">
               <text class="label">租期</text>
               <text class="value">{{myApply.minRentalPeriod}}个月</text>
            </view>
         </view>
         <view class="apply-btns">
            <button size="mini" type="primary" @click="editApply">编辑</button>
            <button size="mini" type="warn" @click="deleteApply">删除</button>
         </view>
      </view>

      <!-- 分享图标 -->
      <!-- <view class="share-icon" v-if="isOwner" @click="shareSpot">
         <uni-icons type="share" size="24"></uni-icons>
      </view> -->

      <!-- 底部操作栏 -->
      <view class="footer">
         <!-- 车位所有者显示编辑和删除按钮 -->
         <template v-if="isOwner">
            <button class="footer-btn edit" @click="editSpot">编辑</button>
            <button class="footer-btn delete" @click="deleteSpot">删除</button>
            <button class="footer-btn qrcode" @click="showPageQrCode">生成页面二维码</button>
         </template>
         <!-- 非车位所有者显示发送意向按钮 -->
         <button v-else-if="!myApply" class="contact-btn" type="primary" @click="showApplyDialog">发送意向</button>
         <button v-else class="footer-btn qrcode" @click="showPageQrCode">生成页面二维码</button>
      </view>

      <!-- 小程序码弹窗 -->
      <uni-popup v-model="showQrCodePopup" mode="center">
         <view class="qr-code-popup">
            <view class="qr-code-header">
               <text class="qr-code-title">车位分享码</text>
               <text class="qr-code-close" @click="closeQrCodePopup">×</text>
            </view>
            <view class="qr-code-content">
               <image :src="qrCodeImage" mode="aspectFit" class="qr-code-image"></image>
               <text class="qr-code-tip">请保存二维码分享给他人</text>
            </view>
         </view>
      </uni-popup>

      <!-- 图片预览弹窗 -->
      <uni-popup ref="imagePreviewPopup" mode="full">
         <view class="image-preview">
            <image :src="currentImage" mode="aspectFit" class="preview-image" @tap="closeImagePreview"></image>
            <view class="preview-close" @click="closeImagePreview">
               <uni-icons type="close" size="32" color="#fff"></uni-icons>
            </view>
         </view>
      </uni-popup>

      <!-- 页面地址二维码弹窗 -->
      <uni-popup ref="pageQrCodePopup" mode="center">
         <view class="qr-code-popup">
            <view class="qr-code-header">
               <text class="qr-code-title">页面地址二维码</text>
               <text class="qr-code-close" @click="closePageQrCodePopup">×</text>
            </view>
            <view class="qr-code-content">
               <canvas ref="pageQrCodeCanvas" class="qr-code-canvas"></canvas>
               <text class="qr-code-tip">扫描二维码访问当前页面</text>
               <button class="download-btn" @click="downloadPageQrCode">下载二维码</button>
            </view>
         </view>
      </uni-popup>

      <!-- 意向表单弹窗 -->
      <uni-popup ref="popup" type="bottom">
         <view class="popup-content">
            <view class="popup-header">
               <text class="popup-title">{{ myApply ? '编辑意向' : '发送意向' }}</text>
               <text class="popup-close" @click="closePopup">×</text>
            </view>
            <view class="popup-body">
               <view class="form-item">
                  <text class="form-label">联系电话</text>
                  <input class="form-input" v-model="applyForm.phone" placeholder="请输入联系电话" />
               </view>
               <view class="form-item">
                  <text class="form-label">期望价格</text>
                  <input class="form-input" type="number" v-model="applyForm.pricePerMonth"
                     placeholder="请输入期望价格(元/月)" />
               </view>
               <view class="form-item">
                  <text class="form-label">租期</text>
                  <input class="form-input" type="number" v-model="applyForm.minRentalPeriod" placeholder="请输入租期(月)" />
               </view>
            </view>
            <view class="popup-footer">
               <button class="popup-btn cancel" @click="closePopup">取消</button>
               <button class="popup-btn confirm" @click="submitApply">确定</button>
            </view>
         </view>
      </uni-popup>

   </view>
</template>

<script>
   
   import {
      getSpots,
      delMineSpot,
      genMiniCodeForPage
   } from "@/api/parking/spots";
   import {
      sendMyApply,
      updateApply,
      delApply,
      getMyApplyBySpotId
   } from "@/api/parking/apply";
   import QRCode from 'qrcode';

   export default {
      components: {
         
      },
      data() {
         return {
            spot: {},
            photoUrls: [],
            statusOptions: [],
            yesNoOptions: [],
            markers: [],
            myApply: null,
            isOwner: false, // 是否是车位所有者
            applyForm: {
               phone: '',
               pricePerMonth: '',
               minRentalPeriod: '',
               spotId: null
            },
            qrCodeImage: '', // 小程序码图片
            showQrCodePopup: false, // 是否显示小程序码弹窗
            currentImage: '', // 当前预览图片URL
            currentPageUrl: '' // 当前页面URL
         }
      },
      created() {
         this.getDicts('parking_spot_status').then(res => {
            this.statusOptions = res.data;
         });
         this.getDicts('sys_yes_no').then(res => {
            this.yesNoOptions = res.data;
         });
      },
      onLoad(options) {
         if (options.id) {
            this.loadSpotDetail(options.id);
            this.loadMyApply(options.id);
         }

      },
      methods: {
         // 加载车位详情
      loadSpotDetail(id) {
         uni.showLoading({
            title: '加载中...'
         });
         getSpots(id).then(res => {
            this.spot = res.data;
            if (this.spot.photoUrls && typeof this.spot.photoUrls === 'string') {
               this.photoUrls = this.spot.photoUrls.split(',');
            }
            // this.photoUrls = res.data.photoUrls;
            // debugger
            // 判断是否是车位所有者
            this.isOwner = this.spot.createBy === this.$store.state.user.name;

            // 设置地图标记
            if (this.spot.latitude && this.spot.longitude) {
               this.markers = [{
                  id: 1,
                  latitude: this.spot.latitude,
                  longitude: this.spot.longitude,
                  title: this.spot.title,
                  iconPath: '/static/parking48.png'
               }];
            }
            
            // 设置当前页面URL
            this.currentPageUrl = `${window.location.origin}${window.location.pathname}?id=${id}`;

            uni.hideLoading();
         }).catch(err => {
            console.error('加载详情失败:', err);
            uni.hideLoading();
            uni.showToast({
               title: '加载失败',
               icon: 'none'
            });
         });
      },
         
         // 分享车位生成小程序码
         shareSpot() {
            uni.showLoading({
               title: '生成中...'
            });
            
            genMiniCodeForPage({
               page: 'pages/parking/detail/index',
               scene: `id=${this.spot.id}`
            }).then(res => {
               uni.hideLoading();
               // 将二进制数据转换为base64图片
               if (res.data) {
                  const arrayBuffer = res.data;
                  const blob = new Blob([arrayBuffer], { type: 'image/png' });
                  const reader = new FileReader();
                  reader.onloadend = () => {
                     this.qrCodeImage = reader.result;
                     this.showQrCodePopup = true;
                  };
                  reader.readAsDataURL(blob);
               } else {
                  uni.showToast({
                     title: '生成失败',
                     icon: 'none'
                  });
               }
            }).catch(err => {
               console.error('生成小程序码失败:', err);
               uni.hideLoading();
               uni.showToast({
                  title: '生成失败',
                  icon: 'none'
               });
            });
         },
         
         // 关闭小程序码弹窗
         closeQrCodePopup() {
            this.showQrCodePopup = false;
         },

         // 加载我的意向
         loadMyApply(spotId) {
            getMyApplyBySpotId({
               spotId: spotId
            }).then(res => {
               this.myApply = res.data;
            });
         },

         // 联系车主
         contactOwner() {
            // TODO: 实现联系车主功能
            uni.showToast({
               title: '功能开发中',
               icon: 'none'
            });
         },

         // 显示发送意向对话框
         showApplyDialog() {
            this.$refs.popup.open();
         },

         // 关闭弹窗
         closePopup() {
            this.$refs.popup.close();
         },

         // 提交意向
         submitApply() {
            if (!this.applyForm.phone) {
               uni.showToast({
                  title: '请输入联系电话',
                  icon: 'none'
               });
               return;
            }
            if (!this.applyForm.pricePerMonth) {
               uni.showToast({
                  title: '请输入期望价格',
                  icon: 'none'
               });
               return;
            }
            if (!this.applyForm.minRentalPeriod) {
               uni.showToast({
                  title: '请输入租期',
                  icon: 'none'
               });
               return;
            }

            uni.showLoading({
               title: '提交中...'
            });

            const applyData = {
               ...this.applyForm,
               spotId: this.spot.id
            };

            if (this.myApply) {
               // 更新意向
               updateApply({
                  ...applyData,
                  id: this.myApply.id
               }).then(() => {
                  uni.hideLoading();
                  this.myApply = {
                     ...applyData,
                     id: this.myApply.id
                  };
                  uni.showToast({
                     title: '更新成功'
                  });
               }).catch(() => {
                  uni.hideLoading();
                  uni.showToast({
                     title: '更新失败',
                     icon: 'none'
                  });
               });
            } else {
               // 新增意向
               sendMyApply(applyData).then(res => {
                  uni.hideLoading();
                  this.myApply = {
                     ...applyData,
                     id: res.data
                  };
                  uni.showToast({
                     title: '提交成功'
                  });
                  this.closePopup();
               }).catch(() => {
                  uni.hideLoading();
                  uni.showToast({
                     title: '提交失败',
                     icon: 'none'
                  });
               });
            }
         },

         // 编辑意向
         editApply() {
            this.applyForm = {
               ...this.myApply
            };
            this.showApplyDialog();
         },

         // 删除意向
         deleteApply() {
            uni.showModal({
               title: '提示',
               content: '确定要删除该意向吗？',
               success: (res) => {
                  if (res.confirm) {
                     uni.showLoading({
                        title: '删除中...'
                     });
                     delApply(this.myApply.id).then(() => {
                        uni.hideLoading();
                        this.myApply = null;
                        uni.showToast({
                           title: '删除成功'
                        });
                        setTimeout(()=> {
                           uni.navigateBack()
                        }, 3000)
                     }).catch(() => {
                        uni.hideLoading();
                        uni.showToast({
                           title: '删除失败',
                           icon: 'none'
                        });
                     });
                  }
               }
            });
         },

         // 预览图片
         previewImage(url) {
            this.currentImage = url;
            this.$refs.imagePreviewPopup.open();
         },

         // 关闭图片预览
         closeImagePreview() {
            this.$refs.imagePreviewPopup.close();
         },

         // 编辑车位
         editSpot() {
            uni.navigateTo({
               url: `/pages/parking/publish/index?id=${this.spot.id}`
            });
         },

         // 删除车位
         deleteSpot() {
            uni.showModal({
               title: '提示',
               content: '确定要删除该车位吗？',
               success: (res) => {
                  if (res.confirm) {
                     uni.showLoading({
                        title: '删除中...'
                     });
                     delMineSpot(this.spot.id).then(() => {
                        uni.hideLoading();
                        uni.showToast({
                           title: '删除成功'
                        });
                        setTimeout(() => {
                           uni.navigateBack();
                        }, 1500);
                     }).catch(() => {
                        uni.hideLoading();
                        uni.showToast({
                           title: '删除失败',
                           icon: 'none'
                        });
                     });
                  }
               }
            });
         },
         
         // 显示页面二维码弹窗
         showPageQrCode() {
            this.$refs.pageQrCodePopup.open();
            this.generatePageQrCode();
         },
         
         // 生成页面二维码
         generatePageQrCode() {
            try {
               debugger;
               console.log(this.$refs)
               const canvas = this.$refs.pageQrCodeCanvas.$el;//document.getElementById('pageQrCodeCanvas');
               if (canvas) {
                  QRCode.toCanvas(canvas, this.currentPageUrl, {
                     width: 200,
                     margin: 1,
                     color: {
                       dark: '#000000',
                       light: '#ffffff'
                     }
                  }, (error) => {
                     if (error) {
                       console.error('生成二维码失败:', error);
                       uni.showToast({
                         title: '生成二维码失败',
                         icon: 'none'
                       });
                     }
                   });
               }
            } catch (error) {
               console.error('生成二维码失败:', error);
               uni.showToast({
                 title: '生成二维码失败',
                 icon: 'none'
               });
            }
         },
         
         // 下载页面二维码
         downloadPageQrCode() {
            try {
               const canvas = document.getElementById('pageQrCodeCanvas');
               if (canvas) {
                  // 创建临时链接
                  const imgDataUrl = canvas.toDataURL('image/png');
                  
                  // 创建下载链接
                  const link = document.createElement('a');
                  link.download = `页面二维码_${new Date().getTime()}.png`;
                  link.href = imgDataUrl;
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
                  
                  // 提示下载成功
                  uni.showToast({
                    title: '下载成功',
                    icon: 'success'
                  });
               }
            } catch (error) {
               console.error('下载二维码失败:', error);
               uni.showToast({
                 title: '下载失败',
                 icon: 'none'
               });
            }
         }
      }
   }</script>

<style scoped>
   .container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      background-color: #f5f5f5;
   }

   .content {
      flex: 1;
      padding-bottom: 40rpx;
   }

   .swiper {
      height: 400rpx;
   }

   .swiper-image {
      width: 100%;
      height: 100%;
   }

   .info-section {
      padding: 30rpx;
      background-color: #fff;
      margin-bottom: 20rpx;
   }

   .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
   }

   .price {
      font-size: 40rpx;
      color: #ff4d4f;
      font-weight: bold;
      margin-bottom: 20rpx;
   }

   .meta {
      display: flex;
      justify-content: space-between;
      font-size: 28rpx;
      color: #666;
   }

   .detail-section {
      padding: 30rpx;
      background-color: #fff;
      margin-bottom: 20rpx;
   }

   .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
   }

   .detail-item {
      display: flex;
      margin-bottom: 20rpx;
   }

   .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #666;
   }

   .value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
   }

   .map-section {
      padding: 30rpx;
      background-color: #fff;
   }

   .map {
      width: 100%;
      height: 400rpx;
      border-radius: 12rpx;
   }

   .share-icon {
      position: fixed;
      top: 70rpx;
      right: 30rpx;
      width: 80rpx;
      height: 80rpx;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
      z-index: 999;
   }

   .footer {
      height: 100rpx;
      background-color: #fff;
      display: flex;
      align-items: center;
      padding: 30rpx 30rpx;
      box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
      gap: 20rpx;
   }

   .footer-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      border-radius: 40rpx;
   }
   
   .footer-btn.qrcode {
      background-color: #1890ff;
   }

   .footer-btn.edit {
      background-color: #007aff;
      color: #fff;
   }

   .footer-btn.delete {
      background-color: #ff4d4f;
      color: #fff;
   }

   .contact-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #007aff;
      color: #fff;
      font-size: 32rpx;
      border-radius: 40rpx;
   }

   .apply-info {
      padding: 30rpx;
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
   }

   .apply-tip {
      font-size: 24rpx;
      color: #000000;
      margin-bottom: 30rpx;
      text-align: center;
      background-color: #f8f8f8;
      padding: 12rpx;
      border-radius: 8rpx;
   }

   .apply-content {
      margin-bottom: 30rpx;
      background-color: #f8f8f8;
      border-radius: 12rpx;
      padding: 20rpx;
   }

   .apply-item {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      font-size: 28rpx;
      padding: 16rpx 0;
      border-bottom: 1rpx solid #eee;
   }

   .apply-item:last-child {
      border-bottom: none;
      margin-bottom: 0;
   }

   .apply-item .label {
      color: #666;
      margin-right: 20rpx;
      width: 140rpx;
   }

   .apply-item .value {
      color: #333;
      font-weight: 500;
   }

   .apply-btns {
      display: flex;
      justify-content: flex-end;
      gap: 20rpx;
   }

   .apply-btns button {
      margin: 0;
      font-size: 26rpx;
      padding: 0 30rpx;
      height: 64rpx;
      line-height: 64rpx;
      border-radius: 32rpx;
   }

   .popup-content {
      width: 100%;
      background-color: #fff;
      border-radius: 24rpx 24rpx 0 0;
      overflow: hidden;
   }

   .popup-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      position: relative;
   }

   .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      flex: 1;
   }

   .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 10rpx;
      position: absolute;
      right: 20rpx;
      top: 20rpx;
   }

   .popup-body {
      padding: 40rpx 30rpx;
   }

   .form-item {
      margin-bottom: 40rpx;
   }

   .form-label {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 16rpx;
   }

   .form-input {
      width: 100%;
      height: 88rpx;
      border: 2rpx solid #eee;
      border-radius: 12rpx;
      padding: 0 24rpx;
      font-size: 30rpx;
      box-sizing: border-box;
      background-color: #f8f8f8;
   }

   .form-input:focus {
      border-color: #007aff;
      background-color: #fff;
   }

   .popup-footer {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      gap: 30rpx;
      border-top: 1rpx solid #f5f5f5;
   }

   .popup-btn {
      flex: 1;
      margin: 0;
      height: 88rpx;
      line-height: 88rpx;
      font-size: 32rpx;
      border-radius: 44rpx;
      font-weight: 500;
   }

   .popup-btn.cancel {
      background-color: #f5f5f5;
      color: #666;
   }

   .popup-btn.confirm {
      background-color: #007aff;
      color: #fff;
   }
   
   .qr-code-popup {
      width: 600rpx;
      background-color: #fff;
      border-radius: 24rpx;
      overflow: hidden;
   }
   
   .qr-code-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      position: relative;
   }
   
   .qr-code-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      flex: 1;
   }
   
   .qr-code-close {
      font-size: 40rpx;
      color: #999;
      padding: 10rpx;
      position: absolute;
      right: 20rpx;
      top: 20rpx;
   }
   
   .qr-code-content {
      padding: 40rpx;
      text-align: center;
   }
   
   .qr-code-image {
      width: 300rpx;
      height: 300rpx;
      margin: 0 auto 20rpx;
   }
   
   .qr-code-canvas {
      width: 300rpx;
      height: 300rpx;
      margin: 0 auto 20rpx;
   }
   
   .download-btn {
      margin-top: 20rpx;
      width: 200rpx;
      height: 70rpx;
      line-height: 70rpx;
      font-size: 28rpx;
      background-color: #007aff;
      color: #fff;
      border-radius: 35rpx;
   }
   
   .qr-code-tip {
      font-size: 28rpx;
      color: #666;
   }

   /* 图片预览样式 */
   .image-preview {
      display: flex;
      flex-direction: column;
      height: 100vh;
      width: 100vw;
      background-color: #000000;
      position: relative;
      align-items: center;
      justify-content: center;
   }

   .preview-image {
      max-width: 100%;
      max-height: 100%;
      width: 100%;
      height: 100%;
   }

   .preview-close {
      position: absolute;
      top: 100rpx;
      right: 20rpx;
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 999;
   }
</style>